package com.sunchangpeng.wechat.mp;

import com.sunchangpeng.wechat.core.WechatClient;
import com.sunchangpeng.wechat.core.token.AccessTokenHolder;
import com.sunchangpeng.wechat.core.token.DefaultAccessTokenHolder;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Slf4j
public class MpWechatClientFactory {
    private static MpWechatClientFactory instance = null;
    private static final ConcurrentMap<String, WechatClient> wechatClients = new ConcurrentHashMap<>(64);

    public synchronized static MpWechatClientFactory getInstance() {
        if (instance == null) {
            instance = new MpWechatClientFactory();
        }
        return instance;
    }

    public WechatClient with(MpAppSetting appSetting) {
        String key = key(appSetting);

        if (!wechatClients.containsKey(key)) {
            OkHttpClient okHttpClient = appSetting.getHttpClient();
            if (okHttpClient == null) {
                okHttpClient = new OkHttpClient();
            }

            AccessTokenHolder accessTokenHolder = appSetting.getAccessTokenHolder();
            if (accessTokenHolder == null) {
                String tokenUrl = EndpointProvider.get("url.token.get");
                accessTokenHolder = new DefaultAccessTokenHolder(okHttpClient, tokenUrl, appSetting.getAppId(), appSetting.getSecret());
                appSetting.setAccessTokenHolder(accessTokenHolder);
            }

            wechatClients.putIfAbsent(key, new WechatClient(okHttpClient, appSetting.getAppId(), appSetting.getSecret(), accessTokenHolder));
        }

        return wechatClients.get(key);
    }

    private String key(MpAppSetting appSetting) {
        return appSetting.getAppId() + ":" + appSetting.getSecret();
    }
}
